<template>
  <view class="dev-settings">
    <view class="header">
      <text class="title">开发者设置</text>
      <text class="subtitle">仅供开发环境使用</text>
    </view>

    <!-- 当前配置显示 -->
    <view class="section">
      <view class="section-title">当前配置</view>
      <view class="config-item">
        <text class="label">BASE_URL:</text>
        <text class="value">{{ currentConfig.BASE_URL }}</text>
      </view>
      <view class="config-item">
        <text class="label">WS_URL:</text>
        <text class="value">{{ currentConfig.WS_URL }}</text>
      </view>
      <view class="config-item">
        <text class="label">环境模式:</text>
        <text class="value">{{ currentConfig.ENV_MODE }}</text>
      </view>
    </view>

    <!-- 预设配置选择 -->
    <view class="section">
      <view class="section-title">快速切换</view>
      <view class="preset-list">
        <view 
          v-for="preset in presetConfigs" 
          :key="preset.mode"
          class="preset-item"
          :class="{ active: preset.mode === currentConfig.ENV_MODE }"
          @tap="selectPreset(preset)"
        >
          <view class="preset-info">
            <text class="preset-name">{{ preset.name }}</text>
            <text class="preset-url">{{ preset.baseUrl }}</text>
          </view>
          <view v-if="preset.mode === currentConfig.ENV_MODE" class="check-icon">✓</view>
        </view>
      </view>
    </view>

    <!-- 自定义配置 -->
    <view class="section">
      <view class="section-title">自定义配置</view>
      
      <view class="form-item">
        <text class="form-label">BASE_URL</text>
        <input 
          v-model="customConfig.baseUrl"
          class="form-input"
          placeholder="请输入后端服务地址"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">WS_URL</text>
        <input 
          v-model="customConfig.wsUrl"
          class="form-input"
          placeholder="请输入WebSocket地址"
        />
      </view>

      <view class="button-group">
        <button 
          class="btn btn-primary"
          @tap="saveCustomConfig"
          :disabled="!isCustomConfigValid"
        >
          保存自定义配置
        </button>
        <button 
          class="btn btn-secondary"
          @tap="testConnection"
          :disabled="!currentConfig.BASE_URL"
        >
          测试连接
        </button>
      </view>
    </view>

    <!-- 重置配置 -->
    <view class="section">
      <view class="section-title">重置配置</view>
      <button 
        class="btn btn-danger"
        @tap="resetConfig"
      >
        恢复默认设置
      </button>
    </view>

    <!-- 连接测试结果 -->
    <view v-if="testResult" class="section">
      <view class="section-title">连接测试结果</view>
      <view class="test-result" :class="{ success: testResult.success, error: !testResult.success }">
        <text class="result-text">{{ testResult.message }}</text>
        <text v-if="testResult.details" class="result-details">{{ testResult.details }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getCurrentConfig, updateDevConfig, resetDevConfig, getPresetConfigs, validateUrl } from '../../utils/config.js'
import { get } from '../../services/request.js'

export default {
  name: 'DevSettings',
  data() {
    return {
      currentConfig: {},
      presetConfigs: [],
      customConfig: {
        baseUrl: '',
        wsUrl: ''
      },
      testResult: null
    }
  },
  computed: {
    isCustomConfigValid() {
      return this.customConfig.baseUrl && 
             this.customConfig.wsUrl && 
             validateUrl(this.customConfig.baseUrl) && 
             validateUrl(this.customConfig.wsUrl)
    }
  },
  onLoad() {
    this.loadConfig()
  },
  methods: {
    // 加载配置
    loadConfig() {
      this.currentConfig = getCurrentConfig()
      this.presetConfigs = getPresetConfigs()
      
      // 初始化自定义配置
      this.customConfig = {
        baseUrl: this.currentConfig.BASE_URL,
        wsUrl: this.currentConfig.WS_URL
      }
    },

    // 选择预设配置
    async selectPreset(preset) {
      try {
        const success = updateDevConfig({
          ENV_MODE: preset.mode,
          DEV_BASE_URL: preset.baseUrl,
          DEV_WS_URL: preset.wsUrl
        })

        if (success) {
          this.loadConfig()
          uni.showToast({
            title: '配置已切换',
            icon: 'success',
            duration: 1500
          })
          
          // 延迟重启应用
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/home/index'
            })
          }, 1500)
        } else {
          throw new Error('保存配置失败')
        }
      } catch (error) {
        uni.showToast({
          title: '切换失败: ' + error.message,
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 保存自定义配置
    async saveCustomConfig() {
      if (!this.isCustomConfigValid) {
        uni.showToast({
          title: '请输入有效的URL地址',
          icon: 'none'
        })
        return
      }

      try {
        const success = updateDevConfig({
          ENV_MODE: 'custom',
          CUSTOM_BASE_URL: this.customConfig.baseUrl,
          CUSTOM_WS_URL: this.customConfig.wsUrl
        })

        if (success) {
          this.loadConfig()
          uni.showToast({
            title: '配置已保存',
            icon: 'success',
            duration: 1500
          })
          
          // 延迟重启应用
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/home/index'
            })
          }, 1500)
        } else {
          throw new Error('保存配置失败')
        }
      } catch (error) {
        uni.showToast({
          title: '保存失败: ' + error.message,
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 测试连接
    async testConnection() {
      this.testResult = null
      
      uni.showLoading({
        title: '测试连接中...'
      })

      try {
        const startTime = Date.now()
        
        // 测试健康检查接口
        const response = await get('/health', {}, {
          timeout: 10000,
          showLoading: false
        })
        
        const endTime = Date.now()
        const responseTime = endTime - startTime

        this.testResult = {
          success: true,
          message: '连接成功',
          details: `响应时间: ${responseTime}ms`
        }

      } catch (error) {
        this.testResult = {
          success: false,
          message: '连接失败',
          details: error.message
        }
      } finally {
        uni.hideLoading()
      }
    },

    // 重置配置
    async resetConfig() {
      try {
        const res = await uni.showModal({
          title: '确认重置',
          content: '确定要恢复默认配置吗？应用将重新启动。',
          confirmText: '确定',
          cancelText: '取消'
        })

        if (res.confirm) {
          const success = resetDevConfig()
          
          if (success) {
            uni.showToast({
              title: '配置已重置',
              icon: 'success',
              duration: 1500
            })
            
            // 延迟重启应用
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/home/index'
              })
            }, 1500)
          } else {
            throw new Error('重置配置失败')
          }
        }
      } catch (error) {
        uni.showToast({
          title: '重置失败: ' + error.message,
          icon: 'none',
          duration: 2000
        })
      }
    }
  }
}
</script>

<style scoped>
.dev-settings {
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 24rpx;
  color: #666;
}

.section {
  background: white;
  margin-bottom: 30rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  border-left: 6rpx solid #1890ff;
  padding-left: 20rpx;
}

.config-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.config-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.value {
  font-size: 26rpx;
  color: #333;
  max-width: 400rpx;
  word-break: break-all;
}

.preset-list {
  margin-top: 20rpx;
}

.preset-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 15rpx;
  border-radius: 12rpx;
  border: 2rpx solid #e8e8e8;
  background: #fafafa;
  transition: all 0.3s;
}

.preset-item.active {
  border-color: #1890ff;
  background: #f0f9ff;
}

.preset-info {
  flex: 1;
}

.preset-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.preset-url {
  font-size: 24rpx;
  color: #666;
}

.check-icon {
  font-size: 36rpx;
  color: #1890ff;
  font-weight: bold;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
  font-weight: 500;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background: white;
}

.form-input:focus {
  border-color: #1890ff;
}

.button-group {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  transition: all 0.3s;
}

.btn:disabled {
  opacity: 0.5;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:not(:disabled):active {
  background: #096dd9;
}

.btn-secondary {
  background: #f0f0f0;
  color: #333;
}

.btn-secondary:not(:disabled):active {
  background: #e0e0e0;
}

.btn-danger {
  background: #ff4d4f;
  color: white;
  width: 100%;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
}

.btn-danger:active {
  background: #d9363e;
}

.test-result {
  padding: 20rpx;
  border-radius: 8rpx;
  margin-top: 20rpx;
}

.test-result.success {
  background: #f6ffed;
  border: 1rpx solid #b7eb8f;
}

.test-result.error {
  background: #fff2f0;
  border: 1rpx solid #ffccc7;
}

.result-text {
  font-size: 28rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.test-result.success .result-text {
  color: #52c41a;
}

.test-result.error .result-text {
  color: #ff4d4f;
}

.result-details {
  font-size: 24rpx;
  color: #666;
}
</style>